package com.aliyun.order.server.service.message;

import com.alibaba.fastjson.JSON;

import com.aliyun.order.server.dao.entity.OrderDO;
import com.aliyun.order.server.service.InnerOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.apache.rocketmq.client.apis.producer.TransactionResolution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 订单交易检查器
 *
 * 
 * @date 2024/12/01
 */
@Slf4j
@Component
public class OrderTransactionChecker implements LocalTransactionChecker {

    @Value("${rocketmq.order-success-topic}")
    private String topic;
    @Autowired
    private InnerOrderService innerOrderService;

    @Override
    public TransactionResolution check(MessageView messageView) {
        log.info("messageView={}", JSON.toJSONString(messageView, true));
        String messageId = messageView.getMessageId().toString();
        OrderDO orderDO = innerOrderService.getOrderByUniqueKey(messageId);
        // 订单为空，说明未创建成功，则消息回滚
        if (orderDO == null) {
            return TransactionResolution.ROLLBACK;
        }
        // 订单存在，说明创建成功，则消息提交
        return TransactionResolution.COMMIT;
    }

    @Override
    public String getTopic() {
        return topic;
    }
}